import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

/**
 * @author Amandine
 * 
 */
public class CrazyWriter extends Frame {

	private static final long serialVersionUID = 1L;

	public TextArea text;
	public TextField data;
	SharedObject sentence;
	public static String myName = "";
	public static int top;
	
	/**
	 * @param argv
	 */
	public static void main(String argv[]) {
		if (argv.length != 1) {
			System.out.println("java CrazyWriter <name>");
			return;
		}
		myName = argv[0];

		// initialize the system
		Client.init();

		// look up the CRAZY_READER object in the name server
		// if not found, create it, and register it in the name server
		SharedObject s = Client.lookup("CRAZY");
		if (s == null) {
			s = Client.create(new Sentence(myName));
			Client.register("CRAZY", s);
		}
		// create the graphical part
		new CrazyWriter(s);
	}

	public CrazyWriter(SharedObject s) {
		setLayout(new FlowLayout());

		text = new TextArea(10, 60);
		text.setEditable(false);
		text.setForeground(Color.red);
		add(text);

		data = new TextField(60);
		add(data);

		JButton start_button = new JButton("start");
		start_button.addActionListener(new CrazyWriteListener(this,
				start_button));
		add(start_button);

		setSize(470, 300);
		text.setBackground(Color.black);
		show();

		sentence = s;
	}
}

class CrazyWriteListener implements ActionListener {
	CrazyWriter cR;
	JButton start_button;

	public CrazyWriteListener(CrazyWriter c, JButton button) {
		this.cR = c;
		this.start_button = button;
	}

	public void actionPerformed(ActionEvent e) {

		if (CrazyWriter.top == 0) {
			start_button.setText("Stop");
			new ActionCrazyWriter(cR).start();
		} else {
			CrazyWriter.top = 0;
			start_button.setText("Start");
		}

	}
}

class ActionCrazyWriter extends Thread {

	public CrazyWriter cR;
	public int times=0;
	
	public ActionCrazyWriter(CrazyWriter cR) {
		this.cR = cR;
	}

	@Override
	public void run() {
		CrazyWriter.top = 1;
		while (CrazyWriter.top == 1) {
			try {
				sleep(500);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String s = cR.data.getText();
			// lock the object in read mode
			cR.sentence.lock_write();

			// invoke the method
			((Sentence) cR.sentence.obj).write(CrazyWriter.myName+"wrote:"+s+(++times));
			cR.text.append(((Sentence) cR.sentence.obj).data + "\n");
			try {
				sleep(2000);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// unlock the object
			cR.sentence.unlock();

		}
	}
}